#! /usr/bin/env python3
import json ,functools
import socket, time, sys
import fire

with open('config.json', 'r', encoding='utf-8') as f:
    config = json.load(f)
    PORT = config['PORT']
    ENGROSSPORT = config['ENGROSSPORT']

# 使用装饰器实现
def ApplicationInstance(func):
    # 实现单例模式
    @functools.wraps(func)
    def fun(*args, **kwargs):
        global ENGROSSPORT
        import socket
        try:
            if args is not None and len(args) == 2:
                ENGROSSPORT = args[1]

            s = socket.socket()
            s.bind(('127.0.0.1', ENGROSSPORT))
        except BaseException as e:
            print(e)
            print('already has an instance...')
            return None
        return func(*args, **kwargs)
    return fun

@ApplicationInstance
def start(cport=None, cengrossport=None):
    try:

        global PORT
        from app import app
        from gevent.pywsgi import WSGIServer
        from gevent import monkey
        monkey.patch_all()
        if cport is not None:
            PORT = cport
        http_server = WSGIServer(('0.0.0.0', PORT), app)
        http_server.serve_forever()

    except BaseException as e:
        print(e)

if __name__=="__main__":
    fire.Fire(start)
